package comment

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"strings"

	user "gitee.com/vzerx/proto-contracts/auth"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserCreatePostCommentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserCreatePostCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCreatePostCommentLogic {
	return &UserCreatePostCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserCreatePostCommentLogic) UserCreatePostComment(req *types.UserPostCommentCreateReq) (resp *types.Empty, err error) {
	// 参数验证
	if req.Id <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	if req.UserId <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	if strings.TrimSpace(req.Content) == "" {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.CommentContentEmpty)
	}

	// 检查帖子是否存在
	var post model.CsCommunityPost
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPost{}).
		Where("id = ?", req.Id).Find(&post).Error; err != nil {
		logx.Errorf("查询帖子失败: %v", err)
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if post.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.CommentPostNotFound)
	}

	// 获取用户信息
	userInfo, err := l.svcCtx.User.GetUserInfo(l.ctx, &user.UserInfoReq{
		UserId: req.UserId,
	})
	if err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if userInfo == nil || userInfo.UserId == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.ErrorNotFound)
	}

	// 创建评论对象
	comment := &model.CsCommunityPostComment{
		PostID:         req.Id,
		Pid:            req.Pid,
		Content:        strings.TrimSpace(req.Content),
		IsTopped:       false,
		CreateUser:     req.UserId,
		CreateUsername: userInfo.UserName,
	}

	query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
		Select("post_id", "content", "is_topped", "create_user", "create_username")

	// 如果指定了pid，表示回复评论
	if req.Pid != 0 {
		// 检查父评论是否存在
		var parentComment model.CsCommunityPostComment
		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
			Where("id = ? AND post_id = ?", req.Pid, req.Id).Find(&parentComment).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}

		if parentComment.ID == 0 {
			return nil, e.NewGrpcErr(codes.NotFound, e.CommentNotFound)
		}

		// 设置回复信息
		comment.Pid = req.Pid
		comment.ReplyUser = parentComment.CreateUser
		comment.ReplyUsername = parentComment.CreateUsername

		query.Select("pid", "post_id", "content", "is_topped", "create_user", "create_username", "reply_user", "reply_username")

	}

	// 创建评论
	if err = query.Create(comment).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
